﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace WebApiCoreAuthenticationCenter.Api
{
    public interface IJWTService
    {
        string GetToken(string userName);
    }

    /// <summary>
    /// 代码演示的是对称加密，所以只有一个key，在返回的信息里面是没有的
    /// 非对称加密后台用私钥加密，需要把解密key公开保证别人可以成功解密获取数据
    /// </summary>
    public class JWTService : IJWTService
    {
        private readonly IConfiguration _configuration;
        public JWTService(IConfiguration configuration)
        {
            this._configuration = configuration;
        }

        public string GetToken(string userName)
        {
            Claim[] claims = new Claim[]
            {
                new Claim("Id","idValue"),
                new Claim(ClaimTypes.Name,userName),
                new Claim("NickName","guoguo"),
                new Claim("Role","Administrator"),//传递其他信息
            };
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
            SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            /**
             * Claims (Payload)
             * Claims部分包含了一些与token有关的重要信息，JWT标准规定了一些字段，除此之外可以包含其他任何JSON兼容的字段
             */
            var token = new JwtSecurityToken(
                issuer: _configuration["Issuer"],
                audience: _configuration["Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: credentials);
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }
    }
}
